/**
 * 智慧粮仓 - 粮情检测模块模拟数据
 * 提供模拟的温度和湿度数据，用于开发和测试
 */

// --- 内部状态管理 ---
let _mockDataState = null; // 用于存储当前所有测点的状态

const CABLE_COUNT_REALTIME = 12; // 实时数据模拟的电缆数
const POINT_COUNT_REALTIME = 4;  // 实时数据每根电缆的测点数

/**
 * 初始化模拟数据的状态
 */
function _initializeMockState() {
    _mockDataState = {
        temperatures: {},
        humidities: {}
    };

    for (let cable = 1; cable <= CABLE_COUNT_REALTIME; cable++) {
        for (let point = 1; point <= POINT_COUNT_REALTIME; point++) {
            const tempId = `cable${cable}_temp${point}`;
            const humId = `cable${cable}_humidity${point}`;

            // 初始温度
            if (point === 1) _mockDataState.temperatures[tempId] = getRandomNumber(28, 36);
            else if (point === 2) _mockDataState.temperatures[tempId] = getRandomNumber(25, 32);
            else if (point === 3) _mockDataState.temperatures[tempId] = getRandomNumber(22, 28);
            else _mockDataState.temperatures[tempId] = getRandomNumber(20, 26);
            
            // 初始湿度
            if (point === 1) _mockDataState.humidities[humId] = getRandomNumber(65, 78);
            else if (point === 2) _mockDataState.humidities[humId] = getRandomNumber(60, 72);
            else if (point === 3) _mockDataState.humidities[humId] = getRandomNumber(55, 68);
            else _mockDataState.humidities[humId] = getRandomNumber(50, 65);
        }
    }
}

/**
 * 平滑地更新模拟数据的状态
 */
function _updateMockState() {
    if (!_mockDataState) {
        _initializeMockState();
        return;
    }

    // 更新温度
    for (const id in _mockDataState.temperatures) {
        const currentValue = _mockDataState.temperatures[id];
        const change = getRandomNumber(-0.2, 0.2, 2); // 每次变化的范围
        let newValue = currentValue + change;
        // 保持在合理范围内
        if (newValue > 40) newValue = 40;
        if (newValue < 15) newValue = 15;
        _mockDataState.temperatures[id] = parseFloat(newValue.toFixed(1));
    }

    // 更新湿度
    for (const id in _mockDataState.humidities) {
        const currentValue = _mockDataState.humidities[id];
        const change = getRandomNumber(-0.5, 0.5, 2); // 每次变化的范围
        let newValue = currentValue + change;
        // 保持在合理范围内
        if (newValue > 85) newValue = 85;
        if (newValue < 40) newValue = 40;
        _mockDataState.humidities[id] = parseFloat(newValue.toFixed(1));
    }
}

/**
 * 生成随机数
 * @param {number} min 最小值
 * @param {number} max 最大值
 * @param {number} decimals 小数位数
 * @returns {number} 随机数
 */
function getRandomNumber(min, max, decimals = 1) {
    const random = Math.random() * (max - min) + min;
    return parseFloat(random.toFixed(decimals));
}

/**
 * 生成模拟温度数据
 * @returns {Array} 温度数据数组
 */
function generateMockTemperatureData() {
    // 更新状态
    _updateMockState();

    const data = [];
    for (let cable = 1; cable <= CABLE_COUNT_REALTIME; cable++) {
        for (let point = 1; point <= POINT_COUNT_REALTIME; point++) {
            const id = `cable${cable}_temp${point}`;
            const temp = _mockDataState.temperatures[id];
            
            const pointData = {
                id: id,
                englishName: `Cable${cable}_Temp${point}`,
                chineseName: `${cable}号电缆${point}层温度`,
                value: temp,
                scaleFactor: 1,
                deviceType: 'TEMPERATURE',
                deviceSubType: 'TEMPERATURE_SENSOR',
                unit: '℃',
                status: temp > 35 ? 'ALARM' : (temp > 30 ? 'WARNING' : 'NORMAL')
            };
            data.push(pointData);
        }
    }
    return data;
}

/**
 * 生成模拟湿度数据
 * @returns {Array} 湿度数据数组
 */
function generateMockHumidityData() {
    // 状态已经在获取温度时更新，此处无需重复更新
    if (!_mockDataState) _updateMockState();

    const data = [];
    for (let cable = 1; cable <= CABLE_COUNT_REALTIME; cable++) {
        for (let point = 1; point <= POINT_COUNT_REALTIME; point++) {
            const id = `cable${cable}_humidity${point}`;
            const humidity = _mockDataState.humidities[id];
            
            const pointData = {
                id: id,
                englishName: `Cable${cable}_Humidity${point}`,
                chineseName: `${cable}号电缆${point}层湿度`,
                value: humidity,
                scaleFactor: 1,
                deviceType: 'HUMIDITY',
                deviceSubType: 'HUMIDITY_SENSOR',
                unit: 'RH',
                status: humidity > 75 ? 'ALARM' : (humidity > 65 ? 'WARNING' : 'NORMAL')
            };
            data.push(pointData);
        }
    }
    return data;
}

/**
 * 生成特定电缆的模拟数据
 * @param {number} cableNo 电缆编号
 * @returns {Object} 电缆数据对象
 */
function generateMockCableData(cableNo) {
    const data = {
        id: `cable${cableNo}`,
        name: `${cableNo}号电缆`,
        type: 'MULTI_PARAMETER',
        status: 'NORMAL',
        temperatures: [],
        humidities: []
    };
    
    // 生成温度数据
    for (let point = 1; point <= 4; point++) {
        // 随机生成温度
        let temp;
        if (point === 1) { // 第一层（底层）
            temp = getRandomNumber(28, 36);
        } else if (point === 2) { // 第二层
            temp = getRandomNumber(25, 32);
        } else if (point === 3) { // 第三层
            temp = getRandomNumber(22, 28);
        } else { // 第四层及以上
            temp = getRandomNumber(20, 26);
        }
        
        // 创建测点数据
        const tempData = {
            point: point,
            value: temp,
            unit: '℃',
            status: temp > 35 ? 'ALARM' : (temp > 30 ? 'WARNING' : 'NORMAL'),
            time: new Date().toISOString()
        };
        
        data.temperatures.push(tempData);
        
        // 如果电缆是多参数类型，添加湿度数据
        if (data.type === 'MULTI_PARAMETER') {
            // 随机生成湿度
            let humidity;
            if (point === 1) { // 第一层（底层）
                humidity = getRandomNumber(65, 78);
            } else if (point === 2) { // 第二层
                humidity = getRandomNumber(60, 72);
            } else if (point === 3) { // 第三层
                humidity = getRandomNumber(55, 68);
            } else { // 第四层及以上
                humidity = getRandomNumber(50, 65);
            }
            
            // 创建测点数据
            const humData = {
                point: point,
                value: humidity,
                unit: '%',
                status: humidity > 75 ? 'ALARM' : (humidity > 65 ? 'WARNING' : 'NORMAL'),
                time: new Date().toISOString()
            };
            
            data.humidities.push(humData);
        }
    }
    
    return data;
}

// 将函数暴露到全局作用域
window.generateMockTemperatureData = generateMockTemperatureData;
window.generateMockHumidityData = generateMockHumidityData;
window.generateMockCableData = generateMockCableData;

/**
 * 模拟粮情数据模块
 */
window.MockGrainData = {
  /**
   * 生成测温电缆数据
   */
  getTemperatureCables: function() {
    return {
      success: true,
      data: {
        overallTemperature: 27.1,
        cables: [
          [
            {
              id: 1,
              layers: [
                { name: "第4层", temperature: 35.1 },
                { name: "第3层", temperature: 28.5 },
                { name: "第2层", temperature: 24.2 },
                { name: "第1层", temperature: 22.3 }
              ]
            },
            {
              id: 2,
              layers: [
                { name: "第4层", temperature: 32.7 },
                { name: "第3层", temperature: 28.4 },
                { name: "第2层", temperature: 24.2 },
                { name: "第1层", temperature: 23.4 }
              ]
            },
            {
              id: 3,
              layers: [
                { name: "第4层", temperature: 31.5 },
                { name: "第3层", temperature: 26.3 },
                { name: "第2层", temperature: 27.5 },
                { name: "第1层", temperature: 22.9 }
              ]
            },
            {
              id: 4,
              layers: [
                { name: "第4层", temperature: 35.4 },
                { name: "第3层", temperature: 25.2 },
                { name: "第2层", temperature: 27.6 },
                { name: "第1层", temperature: 23.8 }
              ]
            }
          ],
          [
            {
              id: 5,
              layers: [
                { name: "第4层", temperature: 34.6 },
                { name: "第3层", temperature: 26.3 },
                { name: "第2层", temperature: 22.4 },
                { name: "第1层", temperature: 23.1 }
              ]
            },
            {
              id: 6,
              layers: [
                { name: "第4层", temperature: 30.3 },
                { name: "第3层", temperature: 29.1 },
                { name: "第2层", temperature: 27.4 },
                { name: "第1层", temperature: 24.8 }
              ]
            },
            {
              id: 7,
              layers: [
                { name: "第4层", temperature: 35.9 },
                { name: "第3层", temperature: 27.6 },
                { name: "第2层", temperature: 26.7 },
                { name: "第1层", temperature: 26.0 }
              ]
            },
            {
              id: 8,
              layers: [
                { name: "第4层", temperature: 34.1 },
                { name: "第3层", temperature: 25.0 },
                { name: "第2层", temperature: 22.2 },
                { name: "第1层", temperature: 21.5 }
              ]
            }
          ]
        ]
      }
    };
  },
  
  /**
   * 生成多参数电缆数据
   */
  getMultiParameterCables: function() {
    return {
      success: true,
      data: {
        overallTemperature: 28.2,
        overallHumidity: 65.5,
        cables: [
          [
            {
              id: 1,
              layers: [
                { name: "第4层", temperature: 35.1, humidity: 72.3 },
                { name: "第3层", temperature: 28.5, humidity: 68.1 },
                { name: "第2层", temperature: 24.2, humidity: 64.5 },
                { name: "第1层", temperature: 22.3, humidity: 62.7 }
              ]
            },
            {
              id: 2,
              layers: [
                { name: "第4层", temperature: 32.7, humidity: 71.2 },
                { name: "第3层", temperature: 28.4, humidity: 67.8 },
                { name: "第2层", temperature: 24.2, humidity: 63.9 },
                { name: "第1层", temperature: 23.4, humidity: 62.1 }
              ]
            }
          ],
          [
            {
              id: 3,
              layers: [
                { name: "第4层", temperature: 31.5, humidity: 70.5 },
                { name: "第3层", temperature: 26.3, humidity: 66.2 },
                { name: "第2层", temperature: 27.5, humidity: 67.3 },
                { name: "第1层", temperature: 22.9, humidity: 61.8 }
              ]
            },
            {
              id: 4,
              layers: [
                { name: "第4层", temperature: 35.4, humidity: 73.1 },
                { name: "第3层", temperature: 25.2, humidity: 65.4 },
                { name: "第2层", temperature: 27.6, humidity: 67.9 },
                { name: "第1层", temperature: 23.8, humidity: 62.3 }
              ]
            }
          ]
        ]
      }
    };
  },
  
  /**
   * 获取电缆历史数据
   * @param {number} durationMinutes - 持续时间（分钟）
   */
  getCableHistoryData: function(durationMinutes = 1440) {
    const cableCount = 32; // 电缆数量
    const dataPoints = 60; // 统一为60个数据点，保证图表疏密有致
    const endTime = new Date();
    const timePoints = [];
    
    // 计算每个时间点之间相差的毫秒数
    const timeStepMs = (durationMinutes * 60 * 1000) / (dataPoints - 1);

    for (let i = dataPoints - 1; i >= 0; i--) {
        const time = new Date(endTime.getTime() - i * timeStepMs);
        timePoints.push(this._formatTime(time, durationMinutes <= 60));
    }
    
    // 生成电缆历史数据
    const cableData = [];
    
    // 为每个电缆生成历史数据
    for (let cableId = 1; cableId <= cableCount; cableId++) {
      const baseTemp = 25 + (cableId % 3);
      const baseHumidity = 60 + (cableId % 5);
      
      const tempData = [];
      const humidityData = [];
      
      // 为每个时间点生成数据
      for (let i = 0; i < dataPoints; i++) {
        // 添加一些随机波动，模拟真实数据
        const tempVariation = (Math.random() - 0.5) * 3;
        const humVariation = (Math.random() - 0.5) * 5;
        
        // 添加时间趋势，白天温度略高
        const hourFactor = (i / dataPoints);
        const timeEffect = hourFactor * 2 * Math.sin(i / dataPoints * Math.PI);
        
        const temp = baseTemp + tempVariation + timeEffect;
        const humidity = baseHumidity + humVariation - timeEffect;
        
        tempData.push(parseFloat(temp.toFixed(1)));
        humidityData.push(parseFloat(humidity.toFixed(1)));
      }
      
      cableData.push({
        id: cableId,
        name: `${cableId}号电缆`,
        temperature: tempData,
        humidity: humidityData,
        hasHumidity: cableId <= (cableCount / 2)  // 假设前一半电缆是多参数电缆
      });
    }
    
    return {
      success: true,
      data: {
        timePoints: timePoints,
        cables: cableData
      }
    };
  },
  
  /**
   * 获取空的电缆历史数据
   * 用于测试无数据时的UI表现
   */
  getEmptyCableHistoryData: function() {
    console.log("正在提供模拟的空历史数据...");
    return {
      success: true,
      data: {
        timePoints: [],
        cables: []
      }
    };
  },
  
  /**
   * 格式化时间为 HH:mm 或 HH:mm:ss 格式
   * @param {Date} date 日期对象
   * @param {boolean} withSeconds 是否显示秒
   * @returns {string} 格式化后的时间字符串
   */
  _formatTime: function(date, withSeconds = false) {
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    if (withSeconds) {
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${hours}:${minutes}:${seconds}`;
    }
    return `${hours}:${minutes}`;
  }
}; 